package com.atguigu.gulimall.gulimallauth.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.entity.SocialUser;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.gulimallauth.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import vo.MemberRespVo;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class Oauth2Controller {
    @Autowired
    MemberFeignService memberFeignService;


    // https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3080046989");
        map.put("client_secret", "992c9cdc2e0b11572560409f23b43975");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://192.168.100.116:20000/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse httpResponse = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), null, map);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            String responseData = EntityUtils.toString(httpResponse.getEntity());
            SocialUser socialUser = JSON.parseObject(responseData, SocialUser.class);
            System.out.println(socialUser);

            R r = memberFeignService.socialLogin(socialUser);
            if (r.get("code").equals(0)) {
                Object data = r.get("data");
                String json = JSON.toJSONString(data);
                MemberRespVo memberRespVo = JSON.parseObject(json, MemberRespVo.class);
                log.info("登录信息：用户：{}", memberRespVo.toString());
                return "redirect:http://192.168.100.116:20000/index.html";
            } else {
                return "redirect:http://192.168.100.116:20000/index.html";
            }
        }

        return "redirect:http://192.168.100.116:20000/index.html";
    }
}
